package com.csust.travel.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.csust.travel.entity.NewUsers;
import com.csust.travel.mapper.NewUsersMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class TokenUtils {

    private static NewUsersMapper staticUserMapper;

    @Resource
    NewUsersMapper newUsersMapper;

    @PostConstruct
    public void setUserService() {
        staticUserMapper = newUsersMapper;
    }

    public static String createToken(String userId, String sign) {
        Algorithm algorithm = Algorithm.HMAC256(sign);
        return JWT.create()
                .withSubject(userId)
                .withExpiresAt(new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(60))) // 5分钟后过期
                .sign(algorithm);
    }

//    public static boolean validateToken(String token, String sign) {
//        try {
//            Algorithm algorithm = Algorithm.HMAC256(sign);
//            JWT.require(algorithm)
//                    .withSubject(JWT.decode(token).getSubject())
//                    .build()
//                    .verify(token);
//            return true;
//        } catch (JWTVerificationException e) {
//            return false;
//        }
//    }
//
//    public static NewUsers getCurrentUser() {
//        try {
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            String token = request.getHeader("token");
//            if (StrUtil.isNotBlank(token)) {
//                String userId = JWT.decode(token).getSubject();
//                return staticUserMapper.selectById(Integer.valueOf(userId));
//            }
//        } catch (Exception e) {
//            return null;
//        }
//        return null;
//    }


//    public static NewUsers getUserByToken(String token) {
//        try {
//            if (StrUtil.isNotBlank(token)) {
//                String userId = JWT.decode(token).getSubject();
//                return staticUserMapper.selectById(Integer.valueOf(userId));
//            }
//        } catch (Exception e) {
//            return null;
//        }
//        return null;
//    }
}
